bash script to check if a process instance is running

#!/bin/bash
if [ $# -ne 2 ]
then
echo "$0 process_name instances_count"
exit 1
fi

function count_match {
echo Count Match #Your code goes here
}

function count_mismatch {
echo Count Mismatch #Your code goes here
}

process=$1
exp_count=$2

run_count=`ps eax | grep ${process} | grep -v grep | wc -l`

if [ ${exp_count} -eq ${run_count} ]
then
count_match
else
count_mismatch
fi

Please note “grep -v grep” is not be required for cygwin, but even if you retain it, it doesn’t alter the behavior.

7 responses to “bash script to check if a process instance is running

  1. did you test this script ?
    you have to use
    ps eax | grep ${process} | grep -v grep | wc -l
    if you dont want to count the grep command!

  2. @Vinod
    Thanks for the correction. I had tested this script under Cygwin and it worked just fine. However I incorporated the correction suggested by you and it should work consistently across *NIX.

  3. You may want to correct the shebang as well – remove the blank like in
    #!/bin/bash

  4. @Pernod,
    Thanks for pointing out, I updated my post.
    For those who are curious about ‘shebang’, visit http://en.wikipedia.org/wiki/Shebang_(Unix)

  5. pgrep utility can also be used to achieve the above mentioned task;
    pgrep examines the active processes on the system and reports the process IDs of the processes.

    eg.
    run_count=`pgrep ${process} | wc -l`
    OR more succinctly
    run_count=`pgrep ${process} -c`

  6. This one is the best:

    if [ “$(pidof processname)” ] ; then
    echo ‘Process is running…’
    fi

Leave a comment